package com.lungle.warmdiary.app.service.push;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.PushPost;
import com.lungle.warmdiary.app.utils.LogUtils;

import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by God on 2016/8/27.
 */
public class JPushService {
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    private static final String TAG = JPushService.class.getSimpleName();
    private Context context;

    public JPushService(Context context) {
        this.context = context;
    }

    private final Handler mHandler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(context, (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    JPushInterface.setAliasAndTags(context, null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);

                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }

    };


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }

    };


    private void setTag(String tag) {
        String[] tagArr = tag.split(",");
        LinkedHashSet<String> tagSet = new LinkedHashSet<>();
        for (String st : tagArr) {
            tagSet.add(st);
        }
        tagSet.add("media_user_android");
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));
    }

    private void setAlias(String alias) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    public static void clearAllNotifications(Context context) {
        JPushInterface.clearAllNotifications(context);
    }


    public void register(final String tag, final String alias) {
        JPushInterface.resumePush(context);
        String regid = JPushInterface.getRegistrationID(context);
        Observable.just(JPushInterface.getRegistrationID(context)).subscribeOn(Schedulers.io()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                // nothing to do
            }

            @Override
            public void onError(Throwable e) {
                LogUtils.printLogE(e.getMessage() != null ? e.getMessage() : "register error");
            }

            @Override
            public void onNext(String s) {
                registerOnServer(tag, alias, regid);
            }
        });


    }

    private void registerOnServer(String tag, String alias, String regid) {
        if (!TextUtils.isEmpty(regid)) {
            setTag(tag);
            setAlias(alias);
            PushPost post = new PushPost(regid);
            ApiFactory.getUserApi().pushRegister(post).subscribeOn(Schedulers.io())
                    .subscribe(new BaseSubscriber<Result>() {
                        @Override
                        public void onCompleted() {
                            AppContext.getInstance().setFristInitJPush();
                        }

                        @Override
                        public void onError(Throwable e) {
                            LogUtils.printLogE(String.format(" Jpush register: %s", e.getMessage()));
                        }

                        @Override
                        public void onNext(Result result) {
                            super.onNext(result);
                        }
                    });
        }
    }


    public static void start(Context context) {
        JPushInterface.init(context);
        JPushInterface.setDebugMode(AppConstant.DEBUG);

    }

    public static void stop(Context context) {
        JPushInterface.stopPush(context);
    }

}
